package com.zb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.ZjProductExtendPath;
import com.zb.mapper.ZjProductExtendPathMapper;
import com.zb.service.ZjProductExtendPathService;
import com.zb.vo.ProductExtendPathVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 产品扩展路径表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2023-08-18
 */
@Service
public class ZjProductExtendPathServiceImpl extends ServiceImpl<ZjProductExtendPathMapper, ZjProductExtendPath> implements ZjProductExtendPathService {

    // 新增、修改、删除扩展路径
    @Override
    public void save(Long custAccId, Long productId, List<ProductExtendPathVo> extendPathVos, List<Long> delextendPathIds) {
        if (null != delextendPathIds && !delextendPathIds.isEmpty()) {
            this.removeByIds(delextendPathIds);
        }
        if (null == extendPathVos || extendPathVos.isEmpty()) {
            return;
        }
        List<ZjProductExtendPath> adds = new ArrayList<>();
        List<ZjProductExtendPath> updates = new ArrayList<>();
        ZjProductExtendPath path = null;
        for (ProductExtendPathVo vo : extendPathVos) {
            path = new ZjProductExtendPath();
            BeanUtils.copyProperties(vo, path);
            if (null != path.getId()) {
                updates.add(path);
                continue;
            }
            path.setId(IdWorker.getId());
            path.setCustAccId(custAccId);
            path.setProductId(productId);
            adds.add(path);
        }
        if (!adds.isEmpty()) {
            this.saveBatch(adds);
        }
        if (!updates.isEmpty()) {
            this.updateBatchById(updates);
        }
    }

    // 根据产品ID获取产品扩展连接
    @Override
    public List<ProductExtendPathVo> getByProductId(Long productId) {
        QueryWrapper<ZjProductExtendPath> wrapper = new QueryWrapper<>();
        wrapper.select("id", "name", "path");
        wrapper.eq("product_id", productId);
        return this.list(wrapper).stream().map(vo -> {
            ProductExtendPathVo pathVo = new ProductExtendPathVo();
            pathVo.setId(vo.getId());
            pathVo.setName(vo.getName());
            pathVo.setPath(vo.getPath());
            return pathVo;
        }).toList();
    }

    // 根据产品ID删除产品扩展连接
    @Override
    public void deleteBatchByProductId(List<Long> productIds) {
        if (null == productIds || productIds.isEmpty()) {
            return;
        }
        QueryWrapper<ZjProductExtendPath> wrapper = new QueryWrapper<>();
        wrapper.in("product_id", productIds);
        this.remove(wrapper);
    }
}
